﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Xml;
using PServiceBus.Core.Runtime;
using PServiceBus.WebAPI;
using System.IO;
using Phoenix.ReflectionExtensions;
using PServiceBus.Gateway.Interfaces;
using PServiceBus.Core.Runtime.Configuration;

namespace PServiceBus.Endpoints.WebAPI {
    public partial class Service : ServiceBase {
        private static string _webName;
        private static int _webPort;
        private static string _messageBusType;
        private static bool _secured;
        private static string _certthumbprint;
        private static string _appid;
        public Service() {
            InitializeComponent();
            ServiceName = _webName;
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
        }

        protected override void OnStart(string[] args) {
            DynamicBroker.Broker[_messageBusType].New();
            APIServer.Start(_webPort, secured: _secured, thumbprint: _certthumbprint, appid: _appid);
        }

        protected override void OnStop() {
            APIServer.Stop();
        }

        static void Main(string[] args) {
            if (args.Length < 1)
                throw new ArgumentException("WebAPI Service Require service name to be passed to the command line");
            LoadServiceInfo(String.Join(" ", args));
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
			{ 
				new Service() 
			};
            ServiceBase.Run(ServicesToRun);
        }

        static void LoadServiceInfo(string id) {
            var service = ConfigurationParser.Process("services.xml")
                    .Select(x => x["service"] as Dictionary<string, object>)
                    .Select(x => x.ToDictionary(kv => kv.Key, kv => kv.Value == null ? string.Empty : kv.Value.ToString()))
                    .First(x => x["id"] == id);
            _webName = service["name"];
            _webPort = Convert.ToInt32(service["port"]);
            _messageBusType = service["messageBusType"];
            _secured = Convert.ToBoolean(service["secured"]);
            _certthumbprint = service["certthumbprint"];
            _appid = service["appid"];
            PServiceBus.Services.Web.Configuration.ESBEndpointAddress = service["esbEndpoint"];
            ShellHelper.NetShAddTCPFirewall(_webName, _webPort);
        }
    }
}
